package com.wing.warehouse.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import com.alibaba.nacos.common.utils.CollectionUtils;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.exception.BusinessException;
import com.wing.warehouse.model.request.WarehouseShelfFlatSpaceForm;
import com.wing.warehouse.model.response.WarehouseShelfSpaceVO;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.warehouse.model.entity.WarehouseShelfSpace;
import com.wing.warehouse.model.request.WarehouseShelfSpaceForm;
import com.wing.warehouse.service.WarehouseShelfSpaceService;
import com.wing.web.excel.ExcelUtil;
import com.wing.web.excel.ShelfSpaceExcelIn;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "仓库货架货位管理", tags = "#/warehouse/warehouseShelfSpace")
@RestController("warehouseShelfSpaceController")
@RequestMapping("warehouse/admin/warehouseShelfSpace")
@RequiredArgsConstructor
@Slf4j
public class WarehouseShelfSpaceController {

    private final WarehouseShelfSpaceService warehouseShelfSpaceService;


    @ApiOperation(value = "查询所有仓库货架货位", notes = "搜索")
    @GetMapping("/list")
    public PageResult<WarehouseShelfSpace> list(
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer limit,
            @RequestParam(defaultValue = "create_time") String sort,
            @RequestParam(defaultValue = "asc") String order,
            String code,Long shelfId,Long queryWarehouseId,Long queryWarehouseAreaId,String status){
        Page pg=new Page(page,limit);
        Map queryParam=new HashMap();
        queryParam.put("code",code);
        queryParam.put("shelfId",shelfId);
        queryParam.put("warehouseId",queryWarehouseId);
        queryParam.put("warehouseAreaId",queryWarehouseAreaId);
        queryParam.put("status", status);
       /* queryParam.put("status", WarehouseShelfSpace.Status.enable.getValue());*/

        IPage<WarehouseShelfSpace> list = warehouseShelfSpaceService.pageList4app(pg,queryParam);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }



    @ApiOperation(value = "添加仓库货架货位", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(WarehouseShelfSpaceForm.Add.class) WarehouseShelfSpaceForm warehouseShelfSpaceForm) {
        if (warehouseShelfSpaceService.add(warehouseShelfSpaceForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "添加仓库货架货位", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addFlat")
    public JsonResult addFlat(@Validated(WarehouseShelfFlatSpaceForm.Add.class) WarehouseShelfFlatSpaceForm warehouseShelfFlatSpaceForm) {
        return warehouseShelfSpaceService.addFlat(warehouseShelfFlatSpaceForm);
    }






    @ApiOperation(value = "修改仓库货架货位", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(WarehouseShelfSpaceForm.Update.class) WarehouseShelfSpaceForm warehouseShelfSpaceForm) {
        WarehouseShelfSpace warehouseShelfSpace = warehouseShelfSpaceService.getById(warehouseShelfSpaceForm.getId());
        if(warehouseShelfSpace == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(WarehouseShelfSpace.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(warehouseShelfSpaceForm, warehouseShelfSpace, copyOptions);
        if (warehouseShelfSpaceService.updateById(warehouseShelfSpace)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }

    @ApiOperation(value = "删除仓库货架货位", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "warehouseShelfSpaceId", value = "仓库货架货位id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long warehouseShelfSpaceId) {
        if (warehouseShelfSpaceService.removeById(warehouseShelfSpaceId)) {
            return JsonResult.success("删除成功");
        }
        return JsonResult.fail("删除失败");
    }

    @GetMapping("/findByCode")
    public JsonResult findByCode(String code){
        WarehouseShelfSpaceVO warehouseShelfSpaceVO = warehouseShelfSpaceService.findByCode(code);
        if(warehouseShelfSpaceVO == null){
            return JsonResult.fail("货位号不存在");
        }
        return JsonResult.success(warehouseShelfSpaceVO);
    }

    @ApiOperation(value = "查询采购入库产品库位", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "skuCode", value = "skuCode编号", required = true, dataType = "Long", paramType = "path")
            ,@ApiImplicitParam(name = "warehouseId", value = "仓库id", required = true, dataType = "Long", paramType = "path")
    })
    @GetMapping("/getShelfSpace")
    public JsonResult<List<WarehouseShelfSpaceVO>> getShelfSpace(String skuCode, Long warehouseId){
        List<WarehouseShelfSpaceVO> warehouseShelfSpaceVOList = warehouseShelfSpaceService.getShelfSpace(skuCode, warehouseId);
        return JsonResult.success(warehouseShelfSpaceVOList);
    }



    @ApiOperation(value = "同步畅捷通货位信息", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/syncSpaceCjt")
    public JsonResult syncSpaceCjt() {
        return warehouseShelfSpaceService.syncSpaceCjt();
    }


    @ApiOperation(value = "下载货位导入excel模板")
    @GetMapping("/template")
    public void template(HttpServletResponse response, HttpServletRequest request) throws IOException {
        warehouseShelfSpaceService.template(response, request);
    }



    /**
     * 导入excel
     */
    @ApiOperation(value = "导入excel")
    @PostMapping("/importExcel")
    public JsonResult importExcel(HttpServletRequest request, @RequestParam("file") MultipartFile file) {
        if (file.isEmpty()) {
            return JsonResult.fail("导入文件为空！");
        }
        try {
            //获取原始的文件名
            String originalFilename = file.getOriginalFilename();
            String fileType = originalFilename.substring(originalFilename.lastIndexOf(".") + 1, originalFilename.length());
            ExcelUtil<ShelfSpaceExcelIn> reader = new ExcelUtil<>();
            InputStream is = file.getInputStream();
            List<ShelfSpaceExcelIn> list = reader.read(is, ShelfSpaceExcelIn.class);
            if (CollectionUtils.isEmpty(list)) {
                return JsonResult.fail("请在表格中添加数据！");
            }
            warehouseShelfSpaceService.importExcel(list);
        } catch (BusinessException e) {
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.fail(e.getCode(), e.getMessage());
        } catch (Exception e) {
            //e.printStackTrace();
            log.error("导入文件异常！异常信息:", e);
            return JsonResult.exception("导入文件异常！异常信息:" + e.getMessage());
        }
        return JsonResult.success("导入成功！");
    }

    @ApiOperation(value = "作废仓库货架货位", notes = "修改")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/cancel/{id}")
    public JsonResult cancel(@PathVariable("id") String id) {
        return warehouseShelfSpaceService.cancel(Long.valueOf(id));
    }

    @ApiOperation(value = "恢复仓库货架货位", notes = "修改")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @GetMapping("/recover/{id}")
    public JsonResult recover(@PathVariable("id") String id) {
        return warehouseShelfSpaceService.recover(Long.valueOf(id));
    }



    @ApiOperation(value = "获取仓库信息根据库位编码code", notes = "查询")
    @GetMapping("/getWarehouseInfoBySpaceCode")
    public JsonResult getWarehouseInfoBySpaceCode(String warehouseShelfSpaceCode){
        WarehouseShelfSpaceVO warehouseShelfSpaceVO = warehouseShelfSpaceService.getWarehouseInfoBySpaceCode(warehouseShelfSpaceCode);
        if(warehouseShelfSpaceVO == null){
            return JsonResult.fail("货位号不存在");
        }
        return JsonResult.success(warehouseShelfSpaceVO);
    }
}
